import java.util.Vector;
/**
 * @author Jens & Jeppe
 *
 * The groups implementation of the Gamelogic
 * This file require other files as well to run.
 */
public class JensJeppe implements IGameLogic {
	private int x = 0;
	private int y = 0;
	private int playerID;
	private int dummy = -1;
	private boolean firstPlayer, killMode, movesFirst;
	//private int KillerStartMove = 3;
	private OpeningMoves opening;
	private Vector plies = new Vector<>();
	private VectorPosHandling VPS_Player1 = new VectorPosHandling();
	private VectorPosHandling VPS_Player2 = new VectorPosHandling();
	private MinMaxAlg al;
	private State currentState;

	public JensJeppe() 
	{
		//TODO Write your implementation for this method
		firstPlayer = true;
		killMode = true;
		movesFirst = false;
		al = new MinMaxAlg();
		opening = new OpeningMoves();
		currentState = new State();		
	}
	/**
	 * Initialize game
	 */
	public void initializeGame(int x, int y, int playerID) 
	{
		this.x = x;
		this.y = y;
		this.playerID = playerID;
		//TODO Write your implementation for this method

		killMode = true;
		if (playerID == 1)
			movesFirst = true;
	}
	/**
	 * Checks whenever player1 or -2 has 4 connected 
	 */
	public Winner gameFinished() 
	{	
		
		if(VPS_Player1.getWinnerState(Common.PLAYER1)>= Common.WINNERCOUNT)
		{
			VPS_Player1.showList();	
			return Winner.PLAYER1;
		}
		else
			if(VPS_Player2.getWinnerState(Common.PLAYER2)>= Common.WINNERCOUNT)
			{
				VPS_Player2.showList();
				return Winner.PLAYER2;
			}
			else
				return Winner.NOT_FINISHED;
	}
	/**
	 * insert an coin and update the common map for either player1 or player2
	 */
	public void insertCoin(int column, int playerID)
	{
		//TODO Write your implementation for this method	
		Common.debug("Player "+playerID+" has inserted a coin at "+column);
		
		if(playerID == 1)
		{
			if(currentState.insertElement(column, playerID))
				VPS_Player1.addVectorPos(new VectorPos(column, currentState.getYpos(column)));				
		}
		else 
			if(playerID == 2)
			{
				if(currentState.insertElement(column, playerID))
					VPS_Player2.addVectorPos(new VectorPos(column, currentState.getYpos(column)));			
			}
		plies.addElement(column);
	}
	/**
	 *  Call first hardcoded moves and later our maxMin Alg.
	 */
	public int decideNextMove() 
	{
		int column = -1;
		//TODO Write your implementation for this method
		if (killMode) {
			column = opening.testPly(plies, movesFirst);
			if (column == -2) { // No good column found in OpeningMoves -
				// continue with heuristic/minmax from now on.
				killMode = false;
				return column = al.start(currentState, playerID);
			}
		}
		else	
		{
			// MinMax call
			column = al.start(currentState, playerID);
		}
		return column;
	}

	private void print(String txt) {
		System.out.println(txt);
	}
}
